<template>
  <div class="register-container">
    <div class="register-box">
      <div class="register-left">
        <h2>欢迎注册</h2>
        <p>加入我们的社区，开启全新体验</p>
        <img
          src="https://images.unsplash.com/photo-1551650975-87deedd944c3?ixlib=rb-1.2.1&auto=format&fit=crop&w=300&h=300&q=80"
          alt="注册插图"
          class="register-image"
        />
      </div>
      <div class="register-right">
        <div class="register-form">
          <h3 class="title">创建账号</h3>

          <el-form
            ref="registerForm"
            :model="registerForm"
            :rules="registerRules"
            class="register-form"
            auto-complete="on"
            label-position="left"
          >
            <el-form-item prop="username">
              <el-input
                v-model="registerForm.username"
                placeholder="用户名 (4-50个字符)"
                prefix-icon="el-icon-user"
                clearable
              />
            </el-form-item>

            <el-form-item prop="email">
              <el-input
                v-model="registerForm.email"
                placeholder="邮箱"
                prefix-icon="el-icon-message"
                clearable
              />
            </el-form-item>

            <el-form-item prop="phone">
              <el-input
                v-model="registerForm.phone"
                placeholder="手机号"
                prefix-icon="el-icon-mobile-phone"
                clearable
              />
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                v-model="registerForm.password"
                :type="passwordType"
                placeholder="密码 (6-20位字符)"
                prefix-icon="el-icon-lock"
                clearable
                @keyup.enter.native="handleRegister"
              />
              <span class="show-pwd" @click="showPwd">
                <svg-icon
                  :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
                />
              </span>
            </el-form-item>

            <el-form-item prop="confirmPassword">
              <el-input
                v-model="registerForm.confirmPassword"
                :type="passwordType"
                placeholder="确认密码"
                prefix-icon="el-icon-lock"
                clearable
                @keyup.enter.native="handleRegister"
              />
            </el-form-item>

            <el-form-item prop="avatar">
              <el-upload
                action="#"
                list-type="picture-card"
                :auto-upload="true"
                :file-list="fileList"
                :before-upload="beforeAvatarUpload"
                :class="
                  (limit && fileList.length >= limit) || disabled
                    ? 'upload-disabled'
                    : ''
                "
              >
                <i
                  v-if="!registerForm.avatar"
                  slot="default"
                  class="el-icon-plus"
                ></i>
                <div slot="file" slot-scope="{ file }">
                  <img
                    class="el-upload-list__item-thumbnail"
                    :src="file.url"
                    alt=""
                  />
                  <span class="el-upload-list__item-actions">
                    <span
                      class="el-upload-list__item-preview"
                      @click="handlePictureCardPreview(file)"
                    >
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <span
                      v-if="!disabled"
                      class="el-upload-list__item-delete"
                      @click="handleDownload(file)"
                    >
                      <i class="el-icon-download"></i>
                    </span>
                    <span
                      v-if="!disabled"
                      class="el-upload-list__item-delete"
                      @click="handleRemove(file)"
                    >
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
              </el-upload>
              <CropperImage
                ref="cropperImage"
                @handleUploadSuccess="handleUploadSuccess"
              />
              <!-- <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="" />
              </el-dialog> -->
              <!-- \<div class="avatar-tip">点击上传头像 (可选)</div> -->
            </el-form-item>

            <el-form-item prop="bio">
              <el-input
                v-model="registerForm.bio"
                type="textarea"
                :rows="2"
                placeholder="个人简介 (可选，最多255字符)"
                maxlength="255"
                show-word-limit
              />
            </el-form-item>

            <el-form-item prop="agreement">
              <el-checkbox v-model="registerForm.agreement">
                我已阅读并同意
                <el-link type="primary" :underline="false">用户协议</el-link> 和
                <el-link type="primary" :underline="false">隐私政策</el-link>
              </el-checkbox>
            </el-form-item>

            <el-button
              :loading="loading"
              type="primary"
              style="width: 100%; margin-bottom: 20px"
              @click.native.prevent="handleRegister"
            >
              立即注册
            </el-button>

            <div class="login-link">
              已有账号？
              <el-link type="primary" :underline="false" @click="goToLogin"
                >立即登录</el-link
              >
            </div>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { register } from "@/api/auth"
import CropperImage from "@/components/common/CropperImage.vue"
import { useUploadFile } from "@/utils/minio"

export default {
  name: "RegisterPage",
  components: { CropperImage },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入用户名"))
      } else if (value.length < 4 || value.length > 50) {
        callback(new Error("用户名长度在4到50个字符之间"))
      } else {
        callback()
      }
    }
    const validateEmail = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入邮箱"))
      } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
        callback(new Error("请输入正确的邮箱格式"))
      } else {
        callback()
      }
    }
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入手机号"))
      } else if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error("请输入正确的手机号格式"))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入密码"))
      } else if (value.length < 6 || value.length > 20) {
        callback(new Error("密码长度在6到20个字符之间"))
      } else {
        callback()
      }
    }
    const validateConfirmPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请再次输入密码"))
      } else if (value !== this.registerForm.password) {
        callback(new Error("两次输入密码不一致!"))
      } else {
        callback()
      }
    }
    const validateAgreement = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请阅读并同意用户协议"))
      } else {
        callback()
      }
    }

    return {
      fileList: [],
      limit: 1,
      disabled: false,
      registerForm: {
        username: "",
        email: "",
        phone: "",
        password: "",
        confirmPassword: "",
        avatar: "",
        bio: "",
        agreement: false
      },
      registerRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername }
        ],
        email: [{ required: true, trigger: "blur", validator: validateEmail }],
        phone: [{ required: true, trigger: "blur", validator: validatePhone }],
        password: [
          { required: true, trigger: "blur", validator: validatePassword }
        ],
        confirmPassword: [
          {
            required: true,
            trigger: "blur",
            validator: validateConfirmPassword
          }
        ],
        agreement: [
          { required: true, trigger: "change", validator: validateAgreement }
        ]
      },
      passwordType: "password",
      loading: false,
      imageUrl: ""
    }
  },
  methods: {
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = ""
      } else {
        this.passwordType = "password"
      }
    },
    handleRegister() {
      this.$refs.registerForm.validate(async (valid) => {
        if (valid) {
          this.loading = true
          // 这里替换为实际的注册API调用
          const registerData = {
            username: this.registerForm.username,
            email: this.registerForm.email,
            phone: this.registerForm.phone,
            password: this.registerForm.password,
            avatar: this.registerForm.avatar,
            bio: this.registerForm.bio,
            status: 0 // 根据您的表结构，0表示正常状态
          }
          try {
            await register(registerData)
            this.loading = false
            this.$message.success("注册成功")
            this.$router.push("/login")
          } catch (error) {
            this.loading = false
          }
        } else {
          console.log("表单验证失败")
          return false
        }
      })
    },
    goToLogin() {
      this.$router.push("/login")
    },
    handleAvatarSuccess(res, file) {
      this.registerForm.avatar = URL.createObjectURL(file.raw)
    },
    async handleUploadSuccess(file) {
      const res = await useUploadFile(file)
      if (res) {
        this.registerForm.avatar = res
      }
      this.fileList = [
        {
          name: file.name,
          // eslint-disable-next-line no-undef
          url: minioEndpoint_mini + this.registerForm.avatar
        }
      ]
    },
    async beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png"
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!")
        return false
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!")
        return false
      }
      this.$refs.cropperImage.handleOpen(
        file,
        { autoCropWidth: 200, autoCropHeight: 200 },
        { type: "fixed", sizeWidth: 200, sizeHeight: 200 }
      )
      return false
    },
    handleRemove() {
      this.fileList = []
      this.registerForm.avatar = ""
    }
  }
}
</script>

<style lang="scss" scoped>
.register-container {
  min-height: 100%;
  width: 100%;
  background-color: #f0f2f5;
  background-image: url("https://gw.alipayobjects.com/zos/rmsportal/TVYTbAXWheQpRcWDaDMu.svg");
  background-repeat: no-repeat;
  background-position: center 110px;
  background-size: 100%;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  // padding: 20px;

  .register-box {
    width: 900px;
    height: auto;
    min-height: 500px;
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
    display: flex;
    overflow: hidden;

    .register-left {
      width: 40%;
      background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
      color: #fff;
      padding: 40px;
      display: flex;
      flex-direction: column;
      justify-content: center;

      h2 {
        font-size: 28px;
        margin-bottom: 10px;
      }

      p {
        font-size: 16px;
        margin-bottom: 40px;
        opacity: 0.9;
      }

      .register-image {
        width: 100%;
        margin-top: 30px;
        border-radius: 5px;
        object-fit: cover;
      }
    }

    .register-right {
      width: 60%;
      padding: 40px;

      .register-form {
        height: 100%;
        display: flex;
        flex-direction: column;

        .title {
          font-size: 24px;
          color: #333;
          margin-bottom: 30px;
          text-align: center;
          font-weight: 500;
        }

        // .avatar-uploader {
        //   display: block;
        //   margin: 0 auto;
        //   border: 1px dashed #d9d9d9;
        //   border-radius: 6px;
        //   cursor: pointer;
        //   width: 100px;
        //   height: 100px;
        //   position: relative;
        //   overflow: hidden;
        //   transition: border-color 0.3s;

        //   &:hover {
        //     border-color: #409eff;
        //   }

        //   .avatar-uploader-icon {
        //     font-size: 28px;
        //     color: #8c939d;
        //     width: 100px;
        //     height: 100px;
        //     line-height: 100px;
        //     text-align: center;
        //   }

        //   .avatar {
        //     width: 100%;
        //     height: 100%;
        //     display: block;
        //     object-fit: cover;
        //   }
        // }

        .avatar-tip {
          text-align: center;
          font-size: 12px;
          color: #999;
          margin-top: 10px;
        }

        .login-link {
          font-size: 14px;
          color: #606266;
          text-align: center;
          margin-top: 20px;
        }
      }
    }
  }
}

.show-pwd {
  position: absolute;
  right: 10px;
  top: 7px;
  font-size: 16px;
  color: #889aa4;
  cursor: pointer;
  user-select: none;
}

@media (max-width: 768px) {
  .register-container {
    .register-box {
      width: 100%;
      flex-direction: column;
      height: auto;

      .register-left,
      .register-right {
        width: 100%;
      }

      .register-left {
        padding: 20px;
        text-align: center;

        .register-image {
          display: none;
        }
      }

      .register-right {
        padding: 20px;
      }
    }
  }
}
</style>

<style>
/* .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
} */

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.upload-disabled .el-upload--picture-card {
  display: none;
}
.el-upload-list__item.is-success {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
